<template>
  <div id="">
    <!-- 吸顶tabs 已完成 -->
    <div class="tabsBox ">
      <swiper class="card-swiper" :class="[DotStyle? 'square-dot':'round-dot']" indicator-dots="true" circular="true"
        autoplay="true" interval="5000" duration="500"  indicator-color="#8799a3"
        indicator-active-color="#0081ff">
        <swiper-item v-for="(item,index) in swiperList" @click="viewPic(index)" :key="index"
          :class="cardCur==index?'cur':''">
          <div class="swiper-item animation-fade" style="box-shadow:1px 1px 2px 0px 	#A9A9A9;  border-radius: 30rpx;">
            <img :src="item.swiperPic" mode="aspectFill"></img>
          </div>
        </swiper-item>
      </swiper>


      <div class="column" :class="{fixed: isFixedTop}" id="navbar">
        <div class="tabs">

          <div v-for="(item,index) in bar" :key="index" @click="tabSelect(index)"
            :class="TabCur==index ? 'nav-switch-style':'' " class="tabsItem">
            <text style="top: 6px;">{{item}}</text>
            <div class="textLine" v-if="TabCur==index"></div>
          </div>


        </div>

        <div class="cu-bar search bg-white" @click="search">
          <div class="search-form round">
            <text class="cuIcon-search"></text>
            <input type="text" placeholder="搜索" confirm-type="search"></input>
          </div>
        </div>
      </div>
      <div class="padding-sm flex flex-wrap" style="margin:0 auto;">
        <div class="padding-xs" v-for="(item,index) in ColorList" :key="index" @click="sort(index)">
          <div class="cu-tag" :class="item.name">{{item.title}}</div>
        </div>
      </div>
    </div>


    <div class="container1">
      <div class="allPage ">
        <block v-if="TabCur==0">
          <card :connent="connent"></card>
        </block>
        <block v-if="TabCur==1">
          <card :connent="hot"></card>
        </block>
      </div>
    </div>


    <div v-if="cardNum">
      <div class="toTop text-center " :class="cardNum == true ?'animationLaunchStar':'animationLaunchEnd'"
        @click="toTop">
        <div class="animationTop">
          <img :src="launchImg" style="position:ralative; width: 45px;height: 45px;" />
          <div style="font-size:10px;position:relative;top:-5px" v-if="launchImg != ''"> 回到顶部</div>
        </div>
      </div>
    </div>

    <div class="putTag" :class="putTag == true ?'animationLaunchStar':'animationLaunchEnd'" @click="inPut"
      v-if="putTag">
      <img :src="putImg" />
    </div>
  </div>
</template>

<script>
  import tools from "../../utils/filter"
  import card from '@/components/card'
  const db = wx.cloud.database()
  const _ = db.command
  let listLenFind = 0; //记录"发现"页面列表长度
  let listLenHot = 0; //记录"热榜"页面列表长度
  let listLenFollow = 0; //新增，记录关注动态列表的长度
  let ret = {};
  let incNum = 0;
  let login = true;
  export default {
    data() {
      return {
        bar: ["最新", "热榜"],
        love: false,
        index: 0,
        connent: [],
        hot: [],
        current: '0',
        praiseNow: "praise",
        PageCur: 'square',
        TabCur: 0,
        cardCur: 0,
        swiperList: {},
        cardNum: false,
        launchImg: '', //火箭状态
        putImg: '../../../dist/wx/static/images/putTag.png', //发布按钮
        putTag: true,
        scrollTop: 130,
        navbarInitTop: 0, //导航栏初始化距顶部的距离
        isFixedTop: false, //是否固定顶部
        ColorList: [{
            title: '日常',
            name: 'line-red',
          },
          {
            title: '捞人',
            name: 'line-orange',
          },
          {
            title: '树洞',
            name: 'line-yellow',
          },
          {
            title: '需求',
            name: 'line-olive',
          },
          {
            title: '问答',
            name: 'line-green',
          },
          {
            title: '表白',
            name: 'line-blue',
          }
        ],
        sortTag: ''
      }
    },
    components: {
      card,
    },
    created() {
      wx.showLoading({
        title: '加载中...',
      })
      this.loadData(10, 0);
      this.getSwiperList();
    },
    onShow: function() {
      let that = this;
      //从缓存获取红点数量
      if (wx.getStorageSync('dotsNum') && wx.getStorageSync('dotsNum') != '0') {
        if (wx.getStorageSync('dotsNum') != '0') {
          wx.setTabBarBadge({
            index: 2,
            text: wx.getStorageSync('dotsNum')
          })
        } else {
          wx.removeTabBarBadge({
            index: 2,
          })
        }
      }

      if (this.TabCur == 0) {
        this.refreshLove();
      }
      if (this.TabCur == 1) {
        this.refreshLoveHot();
      }
      if (this.navbarInitTop == 0) {

        //获取节点距离顶部的距离
        wx.createSelectorQuery().select('#navbar').boundingClientRect(function(rect) {
          if (rect && rect.top > 0) {
            var navbarInitTop = parseInt(rect.top);
            that.navbarInitTop = navbarInitTop;
          }
        }).exec();

      }
    },
    onShareAppMessage: function() {
      return {
        title: '快来瞧一瞧佛趣广场吧！',
        path: '/pages/index/index'
      }
    },
    onReady: function() {

      this.hot = [];
      this.loadHotData(10, 0)
    },
    onPullDownRefresh: function() {
      this.initColor()
      if (this.TabCur == 0) {
        this.connent = [];
        this.sortTag = '';
        this.loadData(5, 0);
      }
      if (this.TabCur == 1) {
        this.hot = [];
        this.loadHotData(5, 0);
      }
      wx.stopPullDownRefresh({})
    },
    onReachBottom: function() {
      var that = this
      if (this.TabCur == 0) {
        var page = this.connent.length;
        if (listLenFind != page) {
          if (this.sortTag == '') {
            this.loadData(10, page) //没有选择标签筛选则加载最新动态
          } else {
            this.getSortData(10, page, that.sortTag)
          }
        } else {
          wx.showToast({
            title: '我也是有底线的！',
            icon: 'none'
          })
        }
      }
      if (this.TabCur == 1) {
        var page = this.hot.length
        if (listLenHot != page) {
          this.loadHotData(10, page)
        } else {
          wx.showToast({
            title: '我也是有底线的！',
            icon: 'none'
          })
        }
      }



    },
    //用户点击右上角分享朋友圈
    onShareTimeline: function() {
      return {
        title: '快来瞧瞧佛趣广场',
        query: {
          key: value
        },
        imageUrl: ''
      }
    },
    methods: {
      refreshLoveHot() { //这里更新热榜页面的点赞状态和数量
        if (wx.getStorageSync('retFromDetail')) {
          ret = wx.getStorageSync('retFromDetail')
        } else {
          return
        }
        if (ret.love == true) {
          this['hot[' + ret.index + '].love'] = true;
          this['hot[' + ret.index + '].dynamic.praise'] = ++this.hot[ret.index].dynamic.praise
        }
        if (ret.love == false) {
          this['hot[' + ret.index + '].love'] = false;
          this['hot[' + ret.index + '].dynamic.praise'] = --this.hot[ret.index].dynamic.praise
        }
        wx.removeStorage({
          key: 'retFromDetail',
        }).then(res => {})
      },
      refreshLove() { //这里更新页面的点赞状态和数量
        if (wx.getStorageSync('retFromDetail')) {
          ret = wx.getStorageSync('retFromDetail')
        } else {
          return
        }
        if (ret.love == true) {
          this['connent[' + ret.index + '].love'] = true
          this['connent[' + ret.index + '].dynamic.praise'] = ++this.connent[ret.index].dynamic.praise
        }
        if (ret.love == false) {

          this['connent[' + ret.index + '].love'] = false;
          this['connent[' + ret.index + '].dynamic.praise'] = --this.connent[ret.index].dynamic.praise

        }
        wx.removeStorage({
          key: 'retFromDetail',
        }).then(res => {})
      },
      refreshCom() { //这里更新评论数量
        if (wx.getStorageSync('incNum')) {
          incNum = wx.getStorageSync('incNum')
        } else {
          return
        }
      },
      //获取轮播图数据
      getSwiperList() {
        db.collection('swiper')
          .get()
          .then((res) => {
            this.swiperList = res.data;

            wx.hideLoading({
              success: (res) => {},
            })
          })
      },
      //浏览轮播图
      viewPic(index) {
        let link = this.swiperList[index].link;
        let picUrl = this.swiperList[index].swiperPic;

        if (link) {
          wx.navigateTo({
            url: 'essay/essay?url=' + link,
          })
        } else {
          wx.previewImage({
            current: picUrl, // 当前显示图片的http链接
            urls: this.swiperList.map(item => item.swiperPic) // 需要预览的图片http链接列表
          })
        }

      },
      changTime(data) {
        for (let i = 0; i < data.length; i++) {
          this.connent[i].dynamic.time = tools.timeChn(data[i].dynamic.time);
        }
      },
      //读取数据库中动态的数据
      loadData(num = 10, page = 0) {
        wx.cloud.callFunction({
          name: 'getIndexData',
          data: {
            num: num,
            plate: 1,
            page: page
          }
        }).then(async res => {
          console.log(res.result.data)
          let oldData = this.connent;
          let newData = oldData.concat(res.result.data);
          let that = this;
          let dataWithNUm = await that.commentNum(newData)
          listLenFind = oldData.length;
          this.connent = dataWithNUm;
          this.changTime(newData);
          this.getPraise();
        })

      },
      //计算评论总数
      async commentNum(newComment) {
        for (var i = 0; i < newComment.length; i++) {
          if (newComment[i].dynamic.comment.length == 0) {
            newComment[i].commentNum = 0
          } else {
            var huifuListNum = 0;
            for (var j = 0; j < newComment[i].dynamic.comment.length; j++) {
              huifuListNum += newComment[i].dynamic.comment[j].huifuList.length
            }
            newComment[i].commentNum = newComment[i].dynamic.comment.length + huifuListNum;
          }
        }
        return newComment
      },
      loadHotData(num = 10, page = 0) {
        wx.cloud.callFunction({
          name: 'getIndexData',
          data: {
            num: num,
            plate: 2,
            page: page,
            time: new Date().getTime() - 86400000 * 3000
          }
        }).then(async res => {
          console.log("hot===>", res.result.data)
          let oldData = this.hot;
          let newData = oldData.concat(res.result.data);
          let that = this;
          let dataWithNUm = await that.commentNum(newData)
          listLenHot = oldData.length;

          this.hot = dataWithNUm;
          this.getHotPraise();
        })
      },
      //加载发现点赞数据
      async getPraise() {
        var dataWithPraise = await this.love(this.connent)

        this.connent = dataWithPraise;
      },
      //加载热榜点赞数据
      async getHotPraise() {
        var dataWithPraise = await this.love(this.hot)
        this.hot = dataWithPraise;
      },
      //添加点赞标记
      async love(e) {
        var l = e.length
        for (var i = 0; i < l; i++) {
          var yn = e[i].dynamic.praiserId.indexOf(wx.getStorageSync('openid'))
          if (yn == -1) {
            e[i].love = false
          } else {
            e[i].love = true
          }
        }
        return e
      },
      //点赞更新数据库
      dianzan(e) {
        let id = e.currentTarget.dataset.id
        let index = e.currentTarget.dataset.index
        let that = this;
        this.showPraise(index);
        wx.cloud.callFunction({
          name: "praise",
          data: {
            plate: 0,
            id: id,
            dzrid: wx.getStorageSync('openid')
          }
        })
        if (this.TabCur == 0) {
          if (this.connent[index].love) {
            that.addMessage(index);
          }
        }
        if (this.TabCur == 1) {
          if (this.hot[index].love) {
            that.addMessage(index);
          }
        }
      },
      addMessage(index) {
        if (wx.getStorageSync('openid') != this.connent[index]._openid) //给自己点赞不需要发动态
        {
          if (this.TabCur == 0) {
            var praiseInfo = {
              praiserName: wx.getStorageSync('userInformation').userinfo.name,
              praiserOpenid: wx.getStorageSync('openid'),
              dynamicId: this.connent[index]._id,
              content: this.connent[index].dynamic.inputData,
              time: new Date().getTime(),
              dot: true
            }
            db.collection('message').where({
                _openid: this.connent[index]._openid
              })
              .update({
                data: {
                  praise: _.unshift([praiseInfo])

                }
              })
              .then(res => {})
          }
          if (this.TabCur == 1) {
            var praiseInfo = {
              praiserName: wx.getStorageSync('userInformation').userinfo.name,
              praiserOpenid: wx.getStorageSync('openid'),
              content: this.hot[index].dynamic.inputData,
              time: new Date().getTime(),
              dot: true
            }
            db.collection('message').where({
                _openid: this.hot[index]._openid
              })
              .update({
                data: {
                  praise: _.unshift([praiseInfo])

                }
              })
              .then(res => {})
          }
        }
      },
      //点赞状态改变
      showPraise(index) {
        if (this.TabCur == 0) {
          var connent = this.connent
          if (this.connent[index].love) {
            connent[index].love = false
            connent[index].dynamic.praise--;
            wx.showToast({
              title: '取消点赞',
              icon: 'none',
              duration: 800
            })
          } else {
            connent[index].love = true
            connent[index].dynamic.praise++;
            wx.showToast({
              title: '点赞成功',
              icon: 'success',
              duration: 800
            })
          }
          this.connent = connent;
        }

        if (this.TabCur == 1) {
          var hot = this.hot
          if (this.hot[index].love) {
            hot[index].love = false
            hot[index].dynamic.praise--;
            wx.showToast({
              title: '取消点赞',
              icon: 'none',
              duration: 800
            })
          } else {
            hot[index].love = true
            hot[index].dynamic.praise++;
            wx.showToast({
              title: '点赞成功',
              icon: 'success',
              duration: 800
            })
          }

          this.hot = hot;

        }
      },
      //轮播图点的状态
      DotStyle(e) {
        this.DotStyle = e.detail.value
      },
      tabSelect(index) {
        this.TabCur = index;
        this.sortTag = '';

      },
      //进入详情页
      inDetail: function(e) {
        if (this.TabCur == 0) {
          var connent = JSON.stringify(this.connent[e.currentTarget.dataset.index]);
          wx.navigateTo({
            url: '../detailPage/detailPage?id=' + e.currentTarget.dataset.id + '&openid=' + e.currentTarget
              .dataset.openid + "&connent=" + connent + "&index=" + e.currentTarget.dataset.index,
          })
        }
        if (this.TabCur == 1) {
          var hot = JSON.stringify(this.hot[e.currentTarget.dataset.index]);
          wx.navigateTo({
            url: '../detailPage/detailPage?id=' + e.currentTarget.dataset.id + '&openid=' + e.currentTarget
              .dataset.openid + "&connent=" + hot + "&index=" + e.currentTarget.dataset.index,
          })
        }
      },
      inPersonPage: function(e) {
        wx.navigateTo({
          url: '../personPage/personPage?openid=' + e.currentTarget.dataset.openid,
        })
      },
      showSidebar(e) {
        this.modalName = e.currentTarget.dataset.target
      },
      hideModal(e) {
        this.modalName = null;
      },
      //搜索
      search() {
        wx.navigateTo({
          url: '/pages/search/search',
        })
      },
      // 获取滚动条当前位置
      onPageScroll: function(e) {
        console.log(e)
        var that = this;
        if (e.scrollTop >= 800 && !this.cardNum) {
          this.launchImg = '../../../dist/wx/static/images/launch.png';
          this.cardNum = true;

        } else if (e.scrollTop < 800 && this.cardNum) {

          this.cardNum = false;
          setTimeout(function() {
            that.launchImg = '';
          }, 0)
        }

        if (e.scrollTop > this.scrollTop && this.putTag) {
          setTimeout(function() {

            that.putImg = "";
            that.putTag = false;
          }, 0)
        } else if (e.scrollTop < this.scrollTop && !this.putTag) {
          that.putTag = true;
          setTimeout(function() {
            that.putImg = '../../../dist/wx/static/images/putTag.png'
          }, 500)

        }

        //给scrollTop重新赋值
        setTimeout(function() {
          that.scrollTop = e.scrollTop;
        }, 0)

        var scrollTop = parseInt(e.scrollTop); //滚动条距离顶部高度
        //判断'滚动条'滚动的距离 和 '元素在初始时'距顶部的距离进行判断
        var isSatisfy = scrollTop >= that.navbarInitTop ? true : false;
        //为了防止不停的setData, 这儿做了一个等式判断。 只有处于吸顶的临界值才会不相等
        if (that.isFixedTop === isSatisfy) {
          return false;
        }

        that.isFixedTop = isSatisfy;
      },

      //回到顶部
      toTop(e) { // 一键回到顶部
        if (wx.pageScrollTo) {
          wx.pageScrollTo({
            scrollTop: 0
          })
        } else {
          wx.showModal({
            title: '提示',
            content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
          })
        }
      },
      inPut() {
        wx.navigateTo({
          url: '../put/put',
        })
      },
      initColor() {
        this.ColorList = [{
            title: '日常',
            name: 'line-red',
          },
          {
            title: '捞人',
            name: 'line-orange',
          },
          {
            title: '树洞',
            name: 'line-yellow',
          },
          {
            title: '需求',
            name: 'line-olive',
          },
          {
            title: '问答',
            name: 'line-green',
          },
          {
            title: '表白',
            name: 'line-blue',
          }
        ]

      },
      sort(index) {
        this.initColor();
        this.sortTag = this.ColorList[index].title;
        this.ColorList[index].name = "bg-" + this.ColorList[index].name.substring(5);
        this.TabCur = 0;
        this.connent = [];
        this.getSortData(10, 0, this.sortTag)

      },
      getSortData(num = 10, page = 0, title) {
        wx.showLoading({
          title: '',
        })
        wx.cloud.callFunction({
          name: 'getSort',
          data: {
            num: num,
            plate: title,
            page: page
          }
        }).then(async res => {
          var oldData = this.connent;
          var newData = oldData.concat(res.result.data);
          var that = this;
          var dataWithNUm = await that.commentNum(newData)
          listLenFind = oldData.length;
          this.connent = dataWithNUm;
          this.getPraise();
          wx.hideLoading({
            success: (res) => {},
          })
        })
      }
    }
  }
</script>

<style scoped>
  page {
    background-color: #F8F8FF;
    height: auto;
  }
  .container1 {
    background-color: #F8F8FF;
    width: auto;
    min-height: 100vh;
  }

  .tabsBox {
    background-color: #F8F8FF;
  }
  text {
    position: relative;
    top: 2rpx;
    line-height: 50rpx;
  }

  .search {
    margin-right: 0rpx;
    font-size: 17px;
  }

  .tabs {
    width: 40%;
    height: 80rpx;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: center;
  }

  .allPage {
    margin-bottom: 180rpx;
    position: relative;
    top: 0rpx;
  }
  .animationLaunchStar {
    animation: bounceInUp 2s 1;
  }

  .animationLaunchEnd {
    animation: bounceOutUp 2s 1;
  }

  .animationTop {
    animation: bounce 4s infinite;
  }

  .toTop {
    position: fixed;
    bottom: 120px;
    right: 20px;
  }
  .putTag {
    position: fixed;
    width: 45px;
    height: 45px;
    bottom: 50px;
    right: 20px;
  }

  .putTag image {
    width: 45px;
    height: 45px;
  }

  .card-swiper swiper-item {
    width: 610rpx !important;
    left: 70rpx;
    box-sizing: border-box;
    padding: 10rpx 0rpx 60rpx;
    overflow: initial;
  }
  .card-swiper {
    height: 310rpx !important;
    position: relative;
    top: 0px;
    margin-bottom: 10px;
    margin-top: 10px;
  }

  .card-swiper swiper-item {
    width: 610rpx !important;
    left: 70rpx;
    box-sizing: border-box;
    padding: 6rpx 0rpx 6rpx;
    overflow: initial;
  }

  .tabs {
    position: relative;
    width: 100%;
    float: left;
    height: 30px;
    margin-top: 10px;
  }

  .text-center {
    text-align: center;
    padding-top: 9px;
  }

  .column {
    width: 100%;
    height: 90rpx;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-around;
    background: #fff;
    border-bottom: solid 1px #eee;
    top: 0;
    left: 0;
    z-index: 100;
  }

  .fixed {
    position: fixed;
  }

  .time {
    position: absolute;
    right: 0px;
    top: 0px;
  }
  .cu-bar {
    display: flex;
    position: relative;
    margin-top: 5px;
    align-items: center;
    min-height: 60rpx;
    width: 48%;
    justify-content: space-between;
    margin: 0 auto;
  }

  .tabs {
    position: relative;
    width: 100%;
    height: 80%;
    left: 15px;
    align-items: left;
  }
  .nav-switch-style {
    color: black;
    font-size: 17px;
    font-weight: 600;
  }

  .tabsItem {
    position: relative;
    width: 27%;
    left: -43px;
    height: 30px;
    text-align: center;
  }

  .textLine {
    position: relative;
    width: 80%;
    height: 9px;
    background-color: #14e2e494;
    z-index: 101;
    top: -2px;
    border-radius: 50%;
    margin: 0 auto;
  }

  .padding-xs {
    padding: 10rpx;
    margin: 0 auto;
  }

  .cu-tag {
    font-size: 28rpx;
    vertical-align: middle;
    position: relative;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    box-sizing: border-box;
    padding: 0rpx 16rpx;
    height: 48rpx;
    font-family: Helvetica Neue, Helvetica, sans-serif;
    white-space: nowrap;
  }

</style>
